#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <array>
#include <map>
#include <clocale>

using namespace std;
struct Frequency
{
	int count;
	string word;
};

void ReadBookFromFile(string fileName, vector<string> &book)
{
	string row;
	string word = "";
	ifstream fin;
	fin.open(fileName);
	while (getline(fin, row))
	{
		if (row != "")
		{
			int length = row.size();
			for (int i = 0; i < length; i++)
			{
				char c = row[i];
				if (c == ' ' || c == '.' || c == '?' || c == '!' || c == ',')
				{
					if (!word.empty())
					{
						book.push_back(word);
						word.clear();
					}
				}
				else
				{
					if (isalnum((unsigned char)c))
					c = tolower(c);
					word += c;
				}
			}
		}
	}
	fin.close();
}

Frequency FrequencyOfWord(map<string, int> &wordCount)
{
	Frequency f;
	f.count = 0;
	for (auto &k : wordCount)
	{
		if (k.second > f.count)
		{
			f.word = k.first;
			f.count = k.second;
		}
	}
	return f;
}

//Frequency SearchForSpecificWord(map<string, int> &wordCount)
//{
//	Frequency f;
//	f.count = 0;
//	string searchedWord;
//	cout << "What word would you like to find?" << endl;
//	cin >> searchedWord;
//
//	if ()
//}

void ReadSalaryFromFile(string fileName, vector<int> &salary)
{
	int post;
	string row;
	ifstream fin;
	fin.open(fileName);
	while (getline(fin, row))
	{
		istringstream iss(row);
		if (!row.empty())
		{
			iss >> post;
			salary.push_back(post);
		}
	}
	fin.close();
}

double CountMean(vector<int> &salary)
{
	double mean = 0;
	double size = salary.size();
	for (auto &v : salary)
	{
		mean += v / size;
	}
	return mean;
}

int CountHighest(vector<int> &salary)
{
	int highest = 0;
	for (auto &v : salary)
	{
		if (v > highest)
			highest = v;
	}
	return highest;
}

int CountLowest(vector<int> &salary)
{
	int lowest = 500000;
	for (auto &v : salary)
	{
		if (v < lowest)
		{
			lowest = v;
		}
	}
	return lowest;
}

void Book()
{
	vector<string> book;
	Frequency f;
	map<string, int> wordCount;
	ReadBookFromFile("nils_holgersson.txt", book);
	sort(book.begin(), book.end());
	for_each(begin(book), end(book), [&](string const &s)
	{
		++wordCount[s];
	});
	f = FrequencyOfWord(wordCount);
	cout << "Word: " << f.word << endl << "Count: " << f.count << endl;
}

void Salary()
{
	vector<int> salary;
	ReadSalaryFromFile("salary.txt", salary);
	sort(salary.begin(), salary.end());

	cout << "Mean of salary: " << CountMean(salary) << endl;
	cout << "Highest salary: " << CountHighest(salary) << endl;
	cout << "Lowest salary: " << CountLowest(salary) << endl;
	cout << "Salary posts: " << salary.size() << endl;
}

int main()
{
	setlocale(LC_ALL, "swedish");

	Book();
	Salary();

	system("PAUSE");
	return 0;
}